package servlet;

import bean.Admin;
import bean.PageBean;
import dao.AdminDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.JsonWrapper;
import util.JsonWrapperBuilder;
import util.RequestUtil;
import util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

import static util.ResponseUtil.*;

/**
 * 管理员用户信息管理
 *
 * @author 邓晴予
 */
public class AdminServlet extends HttpServlet {
    private AdminDao adminDao = new AdminDao();

    /**
     * 管理员用户信息获取
     *
     * @author 邓晴予
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String startStr = req.getParameter("start");  //当前页
        String pagesizeStr = req.getParameter("pagesize");  //页记录数
        String typeStr = req.getParameter("type");
        String valueStr = req.getParameter("value");

        JsonWrapper result = new JsonWrapper();

        if (null != startStr && null != pagesizeStr) {
//			分页查询
            int start = 0;
            int pagesize = 0;
            List<Object> resultAdmin;  //查询返回的用户信息

            try {
                if (!StringUtil.isEmpty(startStr)) {
                    start = Integer.parseInt(startStr);
                }
                if (!StringUtil.isEmpty(pagesizeStr)) {
                    pagesize = Integer.parseInt(pagesizeStr);
                }
                PageBean pageBean = new PageBean(start, pagesize);
                resultAdmin = adminDao.adminList(pageBean, new Admin());
                result.setStatus(200);
                result.setMsg("success");

                JSONArray jsonArray = new JSONArray();
                for (Object single : resultAdmin) {
                    JSONObject jsonObject = JsonWrapper.parseFromObject(single);
                    jsonArray.add(jsonObject);
                }
                result.setDataJsonArray("values", jsonArray);
            } catch (Exception e) {
                result.setStatus(401);
                result.setMsg("failed");
            }
        } else if (null != typeStr && null != valueStr) {
//			按条件查询
            Admin admin = new Admin();
            if ("id".equals(typeStr)) {
                admin.setAdminId(valueStr);
            } else if ("username".equals(typeStr)) {
                admin.setUserName(valueStr);
            } else if ("name".equals(typeStr)) {
                admin.setName(valueStr);
            } else if ("adminRoleId".equals(typeStr)) {
                admin.setAdminRoleId(valueStr);
            }
            List<Object> resultAdmin;  //查询返回的用户信息
            try {
                resultAdmin = adminDao.adminList(null, admin);
                result.setStatus(200);  //待定
                result.setMsg("success");

                JSONArray jsonArray = new JSONArray();
                for (Object single : resultAdmin) {
                    JSONObject jsonObject = JsonWrapper.parseFromObject(single);
                    jsonArray.add(jsonObject);
                }
                result.setDataJsonArray("values", jsonArray);
            } catch (Exception e) {
                result.setStatus(401);
                result.setMsg("failed");
            }
        } else {
//			取总记录数
            try {
                int total = adminDao.adminCount(new Admin());

                if (total != 0) {
                    result.setMsg("success");
                } else {
                    result.setMsg("No record!");
                }
                result.setStatus(200);
                result.setDataEntry("total", total);
            } catch (Exception e) {
                result.setStatus(401);  //待定
                result.setMsg("failed");
            }
        }
        write(resp, result);
    }

    /**
     * 管理员用户信息修改
     *
     * @author 邓晴予
     */
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject json = RequestUtil.getJsonFromRequest(req);
        if (json != null) {
            String t = json.getString("t");
            Admin admin = new Admin();
            boolean modified = false;
            admin.setAdminId(json.getString("id"));
            if ("upt".equals(t)) {
                admin.setAdminRoleId(json.getString("roleId"));
                modified = true;
            } else if ("mod".equals(t)) {
                String old = json.getString("old");
                admin.setPassword(old);
                try {
                    // 校验旧密码
                    List<Object> tmp = adminDao.adminList(null, admin);
                    if (tmp.size() > 0) {
                        String first = json.getString("first");
                        String second = json.getString("second");
                        if (first != null && first.equals(second)) {
                            admin.setPassword(first);
                            modified = true;
                        }
                    } else {
                        modified = false;
                    }
                } catch (Exception e) {
                    writeInternalError(resp);
                    return;
                }
            }
            if (modified) {
                try {
                    // 真正开始修改
                    boolean success = adminDao.adminModify(admin);
                    if (success) {
                        write(resp, 200, "success");
                    } else {
                        write(resp, 301, "failed");
                    }
                } catch (Exception e) {
                    writeInternalError(resp);
                }
            } else {
                writeNotModified(resp);
            }
        } else {
            writeBadRequest(resp);
        }
    }

    /**
     * 管理员用户信息删除
     *
     * @author 邓晴予
     */
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JsonWrapperBuilder builder = JsonWrapper.builder();
        try {
            boolean f = adminDao.adminDelete(req.getParameter("id")) > 0;
            builder.setStatus(f ? 200 : 301);
            builder.setMsg(f ? "success" : "failed");
        } catch (Exception e) {
            builder.setStatus(401);
            builder.setMsg("failed");
        }
        write(resp, builder.build());
    }

    /**
     * 管理员用户信息增加
     *
     * @author 邓晴予
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Admin admin = new Admin();
        JsonWrapper result = new JsonWrapper();
        String t = req.getParameter("t");

        if ("add".equals(t)) {
//			管理员添加
            admin.setName(req.getParameter("name"));
            admin.setUserName(req.getParameter("username"));
            admin.setPassword("666666");
            admin.setAdminRoleId(req.getParameter("roleId"));
            try {
                boolean r = adminDao.adminAdd(admin);
                result.setStatus(200);
                result.setMsg("success");
                result.setDataEntry("result", r);
            } catch (Exception e) {
                result.setStatus(401);
                result.setMsg("failed");
            }
        }
        write(resp, result.get());
    }
}
